package com.pfzy.lib.net.convert;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * 自定义 json转换器
 * https://blog.csdn.net/Dr_abandon/article/details/125231639
 * https://blog.csdn.net/kinpowoo/article/details/88668354
 * https://www.jianshu.com/p/4e93b7b2152a
 * https://www.jianshu.com/p/4ff862f14acc
 * https://juejin.cn/post/6844903817046130696
 */
public class JsonConverterFactory extends Converter.Factory {
    private static boolean isEncrypt = true;
    private final Gson gson;

    public static JsonConverterFactory create() {
        /**
         * setLenient 遇到问题，停止解析，以防止报错，功能相对较弱
         * serializeNulls 智能null
         */
        return create(new GsonBuilder().setLenient().serializeNulls().create());
    }

    /**
     * 是否对进入的参数和返回的结果加密解密
     * @param encrypt
     * @return
     */
    public static JsonConverterFactory create(boolean encrypt) {
        isEncrypt = encrypt;
        return create(new GsonBuilder().setLenient().serializeNulls().create());
    }

    public static JsonConverterFactory create(Gson gson) {
        if (gson == null)
            throw new NullPointerException("gson == null");
        return new JsonConverterFactory(gson);
    }

    private JsonConverterFactory(Gson gson) {
        this.gson = gson;
    }

    /**
     * 响应
     * @param type
     * @param annotations
     * @param retrofit
     * @return
     */
    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new JsonResponseBodyConverter(gson, adapter,isEncrypt);
    }

    /**
     * 请求
     * @param type
     * @param parameterAnnotations
     * @param methodAnnotations
     * @param retrofit
     * @return
     */
    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new JsonRequestBodyConverter(gson, adapter,isEncrypt);
    }
}